import { defineStore } from 'pinia'
import { ref } from 'vue'
import { getUserMessages, updateMessageStatus, type UserMessage, type MessagePageResponse } from '../api/message'

export const useMessageStore = defineStore('message', () => {
  // 消息列表
  const messages = ref<UserMessage[]>([])
  const loading = ref(false)
  const currentPage = ref(0)
  const pageSize = ref(10)
  const totalPages = ref(0)
  const totalElements = ref(0)

  // 获取用户消息
  const fetchMessages = async (userId: number, messageType: number, type: number = -1, page: number = 0, size: number = pageSize.value) => {
    loading.value = true
    try {
      const response: MessagePageResponse = await getUserMessages(userId, messageType, page, size, type)
      // 兼容后端返回的postName/resourceName
      messages.value = response.content.map(msg => ({
        ...msg,
        postName: msg.postName || '',
        resourceName: msg.resourceName || ''
      }))
      currentPage.value = response.number
      totalPages.value = response.totalPages
      totalElements.value = response.totalElements
      return response
    } catch (error) {
      console.error('获取消息失败:', error)
      throw error
    } finally {
      loading.value = false
    }
  }

  // 标记消息为已读
  const markAsRead = async (messageId: number) => {
    try {
      await updateMessageStatus(messageId)
      // 更新本地消息状态
      const message = messages.value.find(m => m.id === messageId)
      if (message) {
        message.isRead = 1
      }
    } catch (error) {
      console.error('标记消息已读失败:', error)
      throw error
    }
  }

  // 获取未读消息数量
  const getUnreadCount = (userId: number) => {
    return getUserMessages(userId, 0, 1000, 0).then(response => response.totalElements)
  }

  return {
    messages,
    loading,
    currentPage,
    pageSize,
    totalPages,
    totalElements,
    fetchMessages,
    markAsRead,
    getUnreadCount
  }
})
